﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SR.API
{
    public static class SliderImageUtility
    {
        public static List<SliderImage> GetSliderImages(string siteUrl, string listName, uint count, string linkUrl, string transitionEffect)
        {
            List<SliderImage> images = new List<SliderImage>();
            if (!siteUrl.IsNullOrEmpty() && !listName.IsNullOrEmpty())
            {
                SPWeb web = Utility.GetSPWeb(siteUrl);
                try
                {
                    SPList list = Utility.GetSPList(listName);
                    if (list != null)
                    {
                        SPQuery query = Utility.GetSPQuery();
                        query.RowLimit = count;
                        SPListItemCollection items = list.GetItems(query);

                        foreach (SPListItem item in items)
                        {
                            images.Add(GetSliderImageFromImageListItem(item, linkUrl, transitionEffect));
                        }
                        return images;
                    }
                    else
                    {
                        throw new Exception().AppendException("List does not exist in " + siteUrl + " path!!");
                    }

                }
                catch (ApplicationException ex)
                {
                    throw ex.AppendException(ex.InnerException.ToString() + "cannot find column.");
                }
                catch (Exception ex)
                {
                    throw ex.AppendException("Images cannot be created!!");
                }
            }
            else { throw new Exception().AppendException("SPWeb url or list name cannot be empty!!"); }
        }

        private static SliderImage GetSliderImageFromImageListItem(SPListItem item, string linkUrl, string transitionEffect)
        {
            SliderImage sliderIamge = null;
           
                sliderIamge = new SliderImage(
                     item.GetStringFieldValue("Title"),
                     item.GetStringFieldValue("ServerUrl"),
                     item.GetStringFieldValue(linkUrl),
                     item.GetStringFieldValue("EncodedAbsUrl"),
                     transitionEffect
                     );
            
            return sliderIamge;

        }
    }
}
